<template>
  <div class="vip-club" v-if="!piniaSystem.getIsH5">
    <h2>{{ t('newVip.text1') }}</h2>
    <div class="vip-card">
      <div class="vip-card__item">
        <div class="vip-card__box">
          <img :src="images.birth" alt="">
          <div class="vip-card__box-info">
            <h3>{{ t('newVip.text2') }}</h3>
            <p>{{ t('newVip.text3') }}</p>
          </div>
        </div>
      </div>
      <div class="vip-card__item">
        <div class="vip-card__box">
          <img :src="images.reward" alt="">
          <div class="vip-card__box-info">
            <h3>{{ t('newVip.text4') }}</h3>
            <p>{{ t('newVip.text5') }}</p>
          </div>
        </div>
      </div>
    </div>
    <div class="vip-level">
      <h2>{{ t('newVip.text6') }}</h2>
      <div class="vip-tabs">
        <ZTab
          v-model:navs="vipNavs"
          v-model:active="vipNavsActive"
          layout="left"
          @change="handleVipType"
        >
        </ZTab>
      </div>
      <div class="vip-info-tabs">
        <ZTab
          v-model:navs="vipInfoNavs"
          v-model:active="vipInfoNavsActive"
          layout="left"
          type="linker"
          @change="handleVipInfo"
        >
          <template #toolbar>
            <span>选择要查询的货币: </span>
            <div class="vip-selector">
              <el-select v-model="currency" value-key="currencyId" size="small" class="z-select-prefix" @change="changeCurrency">
                <template #prefix>
                  <img :src="currency.currencyIcon" alt="" class="vip-selector-icons">
                </template>
                <el-option :label="item.currencyName" :value="item" v-for="item in piniaUserinfo.getWallet" :key="item.gameChannel">
                  <div class="vip-info-tabs__selector-options">
                    <img :src="item.currencyIcon" alt="">
                    <span>{{ item.currencyName }}</span>
                  </div>
                </el-option>
              </el-select>
            </div>
          </template>
        </ZTab>
      </div>
      <div class="vip-content" v-if="hasVipType">
        <el-table v-if="vipInfoNavsActive !== 4" :data="vipData" max-height="500" :empty-text="t('BetRecord.Nocontent')">
          <el-table-column :prop="item.prop" :label="item.label" header-align="center" align="center" :key="item.prop" v-for="item in handleChangeColumns">
            <template #default="{row, column, $index}">
              <div v-if="item.prop.indexOf('symbol') >= 0">
                {{ symbolComp(row, item.upgradeCode) }}
              </div>
              <div v-else>{{ row[item.prop] }}</div>
            </template>
          </el-table-column>
        </el-table>
        <div v-else v-html="dialogTipsData.content" class="vip-tips"></div>
      </div>
      <div class="vip-content" v-else>
        <div v-html="noVipTypeTips" class="vip-tips"></div>
      </div>
      <ZPagination
        class="vip-pagination"
        v-model:pagination="pagination"
        :query="getVipList"
      />
    </div>
  </div>
  <div class="vip-club-h5" v-if="piniaSystem.getIsH5">
    <h1 class="vip-back" @click="vipToHome"><IPhArrowLeft /><span>{{ t('home.Home') }}</span></h1>
    <h2>{{ t('newVip.text1') }}</h2>
    <div class="vip-card">
      <div class="vip-card__item">
        <div class="vip-card__box">
          <img :src="images.vip1" alt="">
          <div class="vip-card__box-info">
            <h3>{{ t('newVip.text2') }}</h3>
            <p>{{ t('newVip.text3') }}</p>
          </div>
        </div>
      </div>
      <div class="vip-card__item">
        <div class="vip-card__box">
          <img :src="images.vip2" alt="">
          <div class="vip-card__box-info">
            <h3>{{ t('newVip.text4') }}</h3>
            <p>{{ t('newVip.text5') }}</p>
          </div>
        </div>
      </div>
    </div>
    <div class="vip-level">
      <h2>
        <span>{{ t('newVip.text6') }}</span>
        <div class="vip-change-currency" @click="currencyPickerShow = true">
          <img :src="currency.currencyIcon" alt="">
          <span>{{ currency.currencyName }}</span>
          <i-iconoir-nav-arrow-down/>
        </div>
      </h2>
      <van-popup v-model:show="currencyPickerShow" round position="bottom">
        <van-picker
          :columns="currencyPicker"
          :option-height="`100rem`"
          @cancel="currencyPickerShow = false"
          @confirm="pickerChangeCurrency"
          v-model="selectedValues"
        >
          <template #option="scope">
            {{ scope.text }}
          </template>
        </van-picker>
      </van-popup>
      <ZScroll>
        <span v-for="(i, index) in vipNavs" :key="i.id" :class="{'active': index == vipNavsActive}" @click="handleVipType({nav: i})">{{ i.label }}</span>
      </ZScroll>
      <div class="vip-list-h5">
        <div class="vip-list-h5__item" v-for="item in vipData" :key="item.id" @click="openDetail(item)">
          <h3 class="vip-title-box">
            <span class="vip-list__title">{{ item.name }}</span>
            <span class="vip-list__level">VIP{{ item.vipSort }}</span>
            <span class="vip-list__infos">{{ t('KenoSingle.Details') }}<i-iconoir-nav-arrow-right/></span>
          </h3>
          <dl v-for="column in columnsWelfare.filter((im:any, index: number)=> index > 1)" :key="column.prop">
            <dt>
              {{ item[column.prop] }}
            </dt>
            <dd>
              {{ column.label }}
            </dd>
          </dl>
        </div>
      </div>
    </div>
    <Dialog v-model:visible="dialogConfig.show" v-model:title="dialogConfig.title" :width="dialogConfig.width" :headerFixed="dialogConfig.headerFixed">
      <div class="vip-dialog">
        <h3 class="vip-title-box">
          <span class="vip-list__title">{{ currentDialogVip.name }}</span>
          <span class="vip-list__level">VIP{{ currentDialogVip.vipSort }}</span>
        </h3>
        <div class="vip-dialog__info">
          <div class="vip-dialog__info-item">
            <div class="vip-dialog__title">{{t("newVip.text10")}}</div>
            <div class="" v-for="item in dialogPromotionData.conditions" :key="item.upgradeCode">
              {{ dialogColumnsFilter(item) }}
              <span>{{ symbolComp(dialogPromotionData, item.upgradeCode, 2) }}</span>
            </div>
          </div>
          <div class="vip-dialog__info-item">
            <div class="vip-dialog__title">{{t("newVip.text11")}}</div>
            <div class="" v-for="item in dialogRelegationData.conditions" :key="item.upgradeCode">
              {{ dialogColumnsFilter(item) }}
              <span>{{ symbolComp(dialogRelegationData, item.upgradeCode, 3) }}</span>
            </div>
          </div>
        </div>
        <div class="vip-dialog__content">
          <h4 class="vip-dialog__content-title">{{t("newVip.text12")}}</h4>
          <div v-html="dialogTipsData.content"></div>
        </div>
      </div>
    </Dialog>
  </div>
  <div class="system-main-footer">
    <span>copyright ©  Mini.Bet 2023 All rights reserved.</span>
    <span>Mini.Bet is operated by Bridge Technologies B.V., with the registration number of 160264 and the registered office address of Dr. M.J. Hugenholtzweg 25, Cura ç ao. It is licensed and authorized by the government of Cura ç ao. The main license is # 8048/JAZ 2022 - 024 Operations issued to Antillephone N.V. The payment agent is Bridge Technologies (Cyrus) Limited, with the registered address of 47 Strovolos Avenue, 5th floor, Curista, Strovolos 2018, Nicosia, Cyprus, Registration No. HE 440867</span>
  </div>
</template>

<script setup lang="ts">
import userinfo from '@/store/userinfo';
import system from '@/store/system';
import vipApi from '@/api/modules/vip';
import router from '@/router';

const piniaUserinfo:any = userinfo();
const piniaSystem:any = system();
const route = useRoute();
const { t } = useI18n();

// 监听语言切换
watch(
  () => piniaSystem.getLang.code,
  (val, preVal) => {
    getVipType();
    changeLangVipList();
  },
  { immediate: false, deep: true },
);

// 监听货币切换
watch(
  () => piniaUserinfo.getCurrentWallet,
  (val, preVal) => {
    currency.value = val;
    selectedValues.value = [piniaUserinfo.getCurrentWallet.currencyId]
    getVipType();
    getVipList();
  },
  { immediate: false, deep: true },
);

const images: any = reactive({
  birth: new URL(`../../assets/images/vip/birth.png`, import.meta.url).href,
  reward: new URL(`../../assets/images/vip/reward.png`, import.meta.url).href,
  vip1: new URL(`../../assets/images/vip/vip1.svg`, import.meta.url).href,
  vip2: new URL(`../../assets/images/vip/vip2.svg`, import.meta.url).href,
});

const data: any = reactive({
  vipNavs: [],
  vipNavsActive: 0,
  currentVipId: "",
  vipInfoNavs: [
    {
      active: 1,
      label: computed(()=>t("newVip.text9"))
    },
    {
      active: 2,
      label: computed(()=>t("newVip.text10"))
    },
    {
      active: 3,
      label: computed(()=>t("newVip.text11"))
    },
    {
      active: 4,
      label: computed(()=>t("newVip.text12"))
    },
  ],
  vipInfoNavsActive: route.query.target || 1,
  pagination: {
    total: 0,
    pageSize: 10,
    pageNum: 1
  },
  dialogConfig: {
    show: false,
    title: computed(() => t('KenoSingle.Details')),
    width: "100%",
    headerFixed: false
  },
  vipData: [],
  columnsWelfare: [
    {
      label: computed(() => t("newVip.text7")),
      prop: 'name'
    },
    {
      label: computed(() => t("newVip.text8")),
      prop: 'vipSort'
    },
    {
      label: computed(() => t("newVip.text25")),
      prop: 'vipElevationMoney'
    },
    {
      label: computed(() => t("newVip.text24")),
      prop: 'vipElevationMultiple'
    },
    {
      label: computed(() => t("newVip.text23")),
      prop: 'vipBirthdayMoney'
    },
    {
      label: computed(() => t("newVip.text24")),
      prop: 'vipBirthdayMultiple'
    },
  ],
  columnsExplain: [
    {
      label: computed(() => t("newVip.text7")),
      prop: 'vipGradeName'
    },
    {
      label: computed(() => t("newVip.text8")),
      prop: 'vipSort'
    },
  ],
  columnsTotal: [
    {
      label: computed(() => t("newVip.text17")),
      prop: 'symbol0',
      upgradeCode: 0
    },
    {
      label: computed(() => t("newVip.text14")),
      prop: 'symbol1',
      upgradeCode: 1
    },
    {
      label: computed(() => t("newVip.text16")),
      prop: 'symbol5',
      upgradeCode: 5
    },
    {
      label: computed(() => t("newVip.text13")),
      prop: 'symbol6',
      upgradeCode: 6
    },
    {
      label: computed(() => t("newVip.text15")),
      prop: 'symbol10',
      upgradeCode: 10
    },
    {
      label: computed(() => t("newVip.text18")),
      prop: 'symbol50',
      upgradeCode: 50
    },
    {
      label: computed(() => t("newVip.text19")),
      prop: 'symbol51',
      upgradeCode: 51
    },
    {
      label: computed(() => t("newVip.text20")),
      prop: 'symbol52',
      upgradeCode: 52
    },
    {
      label: computed(() => t("newVip.text21")),
      prop: 'symbol53',
      upgradeCode: 53
    },
    {
      label: computed(() => t("newVip.text22")),
      prop: 'symbol54',
      upgradeCode: 54
    },
  ],
  currency: piniaUserinfo.getCurrentWallet,
  currencyPickerShow: false,
  selectedValues: [piniaUserinfo.getCurrentWallet.currencyId],
  currentDialogVip: {},
  dialogPromotionData: {},
  dialogRelegationData: {},
  dialogTipsData: {},
  dialogColumns: [],
  hasVipType: false, // 是否有当前的游戏币种
  noVipTypeTips: "",
  handleChangeColumns: [],
});
const {
  vipNavs,
  vipNavsActive,
  currentVipId,
  vipInfoNavs,
  vipInfoNavsActive,
  pagination,
  dialogConfig,
  vipData,
  columnsExplain,
  columnsWelfare,
  currency,
  currencyPickerShow,
  selectedValues,
  currentDialogVip,
  dialogPromotionData,
  dialogRelegationData,
  dialogTipsData,
  dialogColumns,
  hasVipType,
  noVipTypeTips,
  handleChangeColumns,
  columnsTotal,
} = toRefs(data);

dialogColumns.value = [...columnsTotal.value];

const dialogColumnsFilter = (item: any) => {
  const currupgrade = dialogColumns.value.find((im:any)=>im.upgradeCode === item.upgradeCode);
  return currupgrade.label;
};

// h5 picker切换
const currencyPicker = computed(()=>{
  return piniaUserinfo.getWallet.map((im:any)=>{
    return {
      ...im,
      text: im.currencyName,
      value: im.currencyId
    }
  });
});

// h5 picker切换
const pickerChangeCurrency = ({selectedOptions}:any) => {
  piniaUserinfo.setCurrentWallet(selectedOptions[0]);
  currencyPickerShow.value = false;
}

// 会员类型
const getVipType = () => {
  vipApi.getVipType({
    currencyId: piniaUserinfo.getCurrentWallet.currencyId
  }).then((response:any)=>{
    if(response.code === 200){
      vipNavs.value = response.data || [];
      changeLangVipType();
      // 如果是h5则查询默认一次
      handleVipType({nav: vipNavs.value[0]});
      hasVipType.value = true;
    }else{
      hasVipType.value = false;
      noVipTypeTips.value = t('newVip.test02');
      ElMessage.error(t('newVip.test02'));
    }
  });
}
getVipType();

// 获取table头列表
const getUpVipTitle = (type?: number) => {
  let columns: any = [];
  let welfareType = type ? type : vipInfoNavsActive.value;
  if(welfareType == 1){
    columns = columnsWelfare.value;
  }else if(welfareType == 2 || welfareType == 3){
    columns = columnsExplain.value;
  }
  vipApi.getUpVipTitle({
    pageNum: 1,
    pageSize: 10,
    vipConfigId: currentVipId.value,
    welfareType: welfareType
  }).then((response: any)=>{
    if(response.code === 200){
      const tableFilterColumns = columnsTotal.value.filter((element:any)=> response.data.some((im:any) => element.upgradeCode == im.upgradeCondition));
      if(welfareType == 2 || welfareType == 3){
        handleChangeColumns.value = [...columns, ...tableFilterColumns];
      }else{
        handleChangeColumns.value = [...columns];
      }
    }
  })
}

// 切换会员类型多语言
const changeLangVipType = () => {
  vipNavs.value.forEach((element:any, index: number) => {
    const current = element.names.find((im:any)=>{
      return im.languageCode === piniaSystem.getLang.code;
    }) || {};
    element.label = current.content;
    element.active = index;
  });
}

// 切换说明
const handleVipInfo = (result: any) => {
  console.log("切换说明", result)
  vipInfoNavsActive.value = result.nav.active;
  queryCurrentData();
}


// 切换vip
const handleVipType = (result: any) => {
  currentVipId.value = result.nav.id;
  vipNavsActive.value = result.nav.active;
  queryCurrentData();
}

// 获取viplist列表
const getVipList = (type?: number) => {
  let welfareType = type ? type : vipInfoNavsActive.value;
  vipApi.getVipList({
    pageNum: pagination.value.pageNum,
    pageSize: pagination.value.pageSize,
    vipConfigId: currentVipId.value,
    welfareType: welfareType
  }).then((response:any)=>{
    console.log(`vip列表${welfareType}`, response);
    if(response.code === 200){
      vipData.value = response.rows || [];
      if(response.rows){
        if(welfareType === 2){
          // 晋级说明
          dialogPromotionData.value = response.rows.find((im:any) => im.vipSort === currentDialogVip.value.vipSort) || {};
        }else if(welfareType === 3){
          // 保级说明
          dialogRelegationData.value = response.rows.find((im:any) => im.vipSort === currentDialogVip.value.vipSort) || {};
        }else if(welfareType === 4){
          // 注意事项
          dialogTipsData.value = response.rows[0] || {};
          if(dialogTipsData.value.conLan){
            dialogTipsData.value.content = (dialogTipsData.value.conLan.find((im:any)=>im.languageCode === piniaSystem.getLang.code) || {}).content;
          }
        }
      }
      changeLangVipList();
    }
  });
}

const queryCurrentData = () => {
  getUpVipTitle();
  getVipList();
}

// 切换会员列表多语言
const changeLangVipList = () => {
  vipData.value.forEach((element:any, index: number) => {
    const current = element.listLan && element.listLan.find((im:any)=>{
      return im.languageCode === piniaSystem.getLang.code;
    }) || {};
    element.name = current.content;
  });
}

// 返回游戏大厅
const vipToHome = () => {
  router.replace({
    path: '/home'
  });
}

// 货币切换
const changeCurrency = (val:any) => {
  piniaUserinfo.setCurrentWallet(val);
}

// 计算逻辑
const symbolComp = (row:any, upgradeCode: number, welfareType?: number) => {
  let val = '', obj = (row.conditions || []).find((im:any) => im.upgradeCode == upgradeCode);
  if (obj) {
    if (vipInfoNavsActive.value == 2 || welfareType == 2) {
      if (obj.elevationConditionType == 1) {
        val = '≥'
      } else if (obj.elevationConditionType == 2) {
        val = '>'
      } else if (obj.elevationConditionType == 3) {
        val = '='
      }
    } else if (vipInfoNavsActive.value == 3 || welfareType == 3) {
      if (obj.relegationConditionType == 1) {
        val = '≥'
      } else if (obj.relegationConditionType == 2) {
        val = '>'
      } else if (obj.relegationConditionType == 3) {
        val = '='
      }
    }
    return val + String(obj.elevationConditionNum)
  }
}

// 打开详情
const openDetail = (item: any) => {
  dialogConfig.value.show = true;
  currentDialogVip.value = item;
  getVipList(2);
  getVipList(3);
  getVipList(4);
}
</script>

<style lang="scss" scoped>
@import url(./index.scss);
</style>
